package com.ruoyi.web.controller.bussiness;

import com.github.pagehelper.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.AsyncUtils;
import com.ruoyi.entity.po.TChatRoomPopularity;
import com.ruoyi.entity.po.TPlayer;
import com.ruoyi.entity.po.TPlayerChatRoom;
import com.ruoyi.entity.po.TUserChatRoomRelation;
import com.ruoyi.entity.vo.ChatRoomPopularityVo;
import com.ruoyi.service.IPlayerService;
import com.ruoyi.service.IPlayerChatRoomService;

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.data.util.Pair;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 选手聊天室(t_player_chat_room)表控制层
 *
 * @author xxxxx
 */
@Slf4j
@RestController
@RequestMapping("/chatRoom")
@Api(tags = "PC-7.选手聊天室管理")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class PlayerChatRoomController extends BaseController {
    /**
     * 服务对象
     */
    private final IPlayerChatRoomService playerChatRoomService;

    private final IPlayerService playerService;

    private final TransactionTemplate transactionTemplate;

    @GetMapping("/list")
    @ApiOperation("查询选手聊天室列表")
    public TableDataInfo list(TPlayerChatRoom playerChatRoom) {
        startPage();
        List<TPlayerChatRoom> list = playerChatRoomService.selectChatRommList(playerChatRoom);
        return getDataTable(list);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    @ApiOperation("查询选手聊天室")
    public TPlayerChatRoom selectOne(Integer id) {
        return playerChatRoomService.selectByPrimaryKey(id);
    }

    @PostMapping("/add")
    @ApiOperation("新增选手聊天室")
    public AjaxResult add(@RequestBody TPlayerChatRoom playerChatRoom) {
        if (playerChatRoomService.selectByPlayerName(playerChatRoom.getPlayerName()) != null) {
            return error("选手聊天室已存在");
        }
        return toAjax(playerChatRoomService.insertSelective(playerChatRoom));
    }

    @PostMapping("/delete")
    @ApiOperation("删除选手聊天室")
    public AjaxResult delete(@RequestBody Integer[] ids) {
        return toAjax(playerChatRoomService.deleteByPrimaryKeys(ids));
    }

    @PostMapping("/edit")
    @ApiOperation("修改选手聊天室")
    public AjaxResult edit(@RequestBody TPlayerChatRoom playerChatRoom) {
        return toAjax(playerChatRoomService.updateByPrimaryKeySelective(playerChatRoom));
    }

    @Log(title = "上传选手聊天室", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadChatRoom")
    @ResponseBody
    @ApiOperation("上传选手聊天室")
    public AjaxResult uploadChatRoom(@RequestParam("excel") MultipartFile file) {
        final var modifyPairs = new ArrayList<Pair<String, String>>();
        try (final InputStream fis = file.getInputStream();
             final Workbook workbook = new XSSFWorkbook(fis)) {
            final Sheet sheet = workbook.getSheetAt(0);
            // 从第一行开始
            for (int i = 1; i < sheet.getLastRowNum(); i++) {
                final Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                final Cell nameCell = row.getCell(0);
                final Cell roomNameCell = row.getCell(1);
                if (nameCell != null && roomNameCell != null) {
                    final String playerName = nameCell.getStringCellValue();
                    final String roomName = roomNameCell.getStringCellValue();
                    if (!StringUtils.hasText(playerName) || !StringUtils.hasText(roomName)) {
                        continue;
                    }
                    modifyPairs.add(Pair.of(playerName, roomName));
                }
            }
        } catch (IOException e) {
            log.error("读取上传选手聊天室 Excel 发生错误", e);
            return error("读取上传选手聊天室 Excel 发生错误");
        }
        if (modifyPairs.isEmpty()) {
            return success("上传的 excel 内容为空");
        }
        transactionTemplate.executeWithoutResult(status -> {
            for (Pair<String, String> modifyPair : modifyPairs) {
                final String playerName = modifyPair.getFirst();
                final String roomName = modifyPair.getSecond();
                final TPlayerChatRoom dbPlayerChatRoom = playerChatRoomService.selectByPlayerName(playerName);
                if (dbPlayerChatRoom != null) {
                    dbPlayerChatRoom.setRoomName(roomName);
                    playerChatRoomService.updateByPrimaryKey(dbPlayerChatRoom);
                } else {
                    final TPlayer player = playerService.selectByName(playerName);
                    if (player != null) {
                        final TPlayerChatRoom playerChatRoom = new TPlayerChatRoom();
                        playerChatRoom.setPlayerName(playerName);
                        playerChatRoom.setPlayerId(player.getId());
                        playerChatRoom.setRoomName(roomName);
                        playerChatRoomService.insert(playerChatRoom);
                    }

                }
            }
        });
        return success("保存成功");
    }



}
